package com.itcast.hotel;

import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class 线程池运行原理 {
    public static volatile boolean flag = true;

    public static void main(String[] args) {
        // 用于演示效果
        new Thread(() -> {
            // 接收控制台参数
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String s = scanner.nextLine();
                // 如果控制输入stop 将flag设置false, 所有任务都会执行完毕
                if ("stop".equals(s)) {
                    flag = false;
                    break;
                }
            }
        }).start();
        // 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
        for (int i = 0; i < 20; i++) {
            try {
                // 循环执行 20个任务
                executor.execute(new MyRunnable("第" + (i + 1) + "号任务"));
            } catch (Throwable e) {
                e.printStackTrace();
                System.out.println("丢弃任务: " + (i + 1));
            }
        }
    }

    static class MyRunnable implements Runnable {
        private String name;

        public MyRunnable(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "==>" + name);
            while (flag) {  // true
                //flag是一个开关，为true时线程任务会一直执行让线程一直执行
            }
        }
    }
}